# -*- coding: utf-8 -*-
from typing import List

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec

from zhi_dao import driver_wait
from zhi_dao.entity.zhidao_course import ZhiDaoCourse
from zhi_dao.http_log.zhidao_http_log import ZhiDaoWebDataObtain
from zhi_dao import driver


class ZhiDaoCourseReader:

    courses: List[ZhiDaoCourse]

    def read_sources(self) -> None:
        course_list_ul = []
        course_list: List[ZhiDaoCourse] = []
        while len(course_list_ul) == 0:
            sharing_class_div = driver_wait.until(ec.presence_of_element_located((By.XPATH,
                                                                                  "//div[@id='sharingClassed']")))
            course_list_ul = sharing_class_div.find_elements(By.XPATH, ".//ul[@class='datalist']")
            for course_ul in course_list_ul:
                left_course_div = course_ul.find_element(By.XPATH, ".//div[@class='item-left-course']")
                course_name_div = left_course_div.find_element(By.XPATH, ".//div[@class='courseName']")
                course_progress = left_course_div.find_element(By.XPATH, ".//span[@class='processNum']")
                zhi_dao_course = ZhiDaoCourse(name=course_name_div.text, progress=course_progress.text,
                                              element=course_progress)
                course_list.append(zhi_dao_course)
        self.courses = course_list

    def read_sources_from_http(self):
        driver_wait.until(ec.presence_of_element_located((By.XPATH, "//div[@id='sharingClassed']")))
        zhi_dao_course_list: List[ZhiDaoCourse] = []
        zhi_dao_web_data_obtain = ZhiDaoWebDataObtain(driver, False)
        query_url = "https://onlineservice-api.zhihuishu.com/gateway/t/v1/student/course/share/queryShareCourseInfo"
        course_url_base = "https://studyvideoh5.zhihuishu.com/stuStudy?recruitAndCourseId="
        course_data = None
        while course_data is None:
            course_data = zhi_dao_web_data_obtain.get_data(query_url)
        course_result = course_data.get("result")
        course_list = course_result.get("courseOpenDtos")
        for course in course_list:
            course_name = course.get("courseName")
            progress = course.get("progress")
            course_url = course_url_base + course.get("secret")
            zhi_dao_course = ZhiDaoCourse(name=course_name, progress=progress,
                                          url=course_url)
            zhi_dao_course_list.append(zhi_dao_course)
        self.courses = zhi_dao_course_list

    def get_courses(self):
        return self.courses

